package com.mazegame.frontend;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mazegame.backend.BackendLoginService;
import com.mazegame.backend.BackgroundPanel;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.geometry.Insets;
import javafx.geometry.Pos;

import javax.swing.*;
import java.awt.*;

public class LoginPanel extends JPanel implements GamePanel {
    private CardLayout cardLayout;
    private JPanel cardPanel;
    private JLayeredPane layeredPane;
    private static final int WIDTH = 1500;
    private static final int HEIGHT = 900;
    private JFXPanel jfxPanel;

    // 静态变量用于存储当前登录的用户信息
    public static String currentUsername;
    public static String currentUserId;

    public LoginPanel(CardLayout cardLayout, JPanel cardPanel) {
        this.cardLayout = cardLayout;
        this.cardPanel = cardPanel;
        initializeUI();
    }

    private void initializeUI() {
        // 使用 JLayeredPane 管理不同层级的组件
        layeredPane = new JLayeredPane();
        setLayout(new BorderLayout());
        add(layeredPane, BorderLayout.CENTER);

        // 创建背景面板并添加到最底层
        BackgroundPanel backgroundPanel = new BackgroundPanel("/img/bk.png");
        backgroundPanel.setBounds(0, 0, WIDTH, HEIGHT);
        layeredPane.add(backgroundPanel, JLayeredPane.DEFAULT_LAYER);

        // 创建 JavaFX 内容面板（登录界面）
        jfxPanel = new JFXPanel();
        jfxPanel.setOpaque(false); // 确保 JFXPanel 透明
        jfxPanel.setBounds(0, 0, WIDTH, HEIGHT);
        layeredPane.add(jfxPanel, JLayeredPane.MODAL_LAYER); // 放在上层

        Platform.runLater(() -> {
            VBox loginBox = createLoginBox();
            // 创建透明场景
            Scene scene = new Scene(loginBox, WIDTH, HEIGHT, Color.TRANSPARENT);
            jfxPanel.setScene(scene);
        });
    }

    private VBox createLoginBox() {
        VBox loginBox = new VBox(30);
        loginBox.setPadding(new Insets(50, 20, 50, 20));
        loginBox.setAlignment(Pos.CENTER);
        loginBox.setPrefWidth(350);
        //-fx-background-color: rgba(0, 0, 0, 0)最后一个参数设置透明度
        loginBox.setStyle("-fx-background-color: rgba(0, 0, 0, 0); -fx-background-radius: 10px;"); // 透明背景

        // 登录标题
        Label loginTitle = new Label("玩家登录");
        loginTitle.setFont(Font.font("Arial", FontWeight.BOLD, 67));
        loginTitle.setTextFill(Color.web("#FFD700"));

        // 用户名输入
        TextField usernameField = createInputBox("用户名");

        // 密码输入
        PasswordField passwordField = createPasswordBox("密码");

        // 登录按钮
        Button loginButton = createButton("登录");
        loginButton.setOnAction(e -> {
            String username = usernameField.getText();
            String password = passwordField.getText();
            if (username.isEmpty() || password.isEmpty()) {
                showAlert("请输入用户名和密码");
                return;
            }
            // 发送请求并解析 JSON 响应
            String jsonResponse = BackendLoginService.login(username, password);
            try {
                JsonObject obj = JsonParser.parseString(jsonResponse).getAsJsonObject();
                String status = obj.get("status").getAsString();
                if ("success".equals(status)) {
                    showAlert("登录成功！欢迎回来，" + username);
                    // 保存当前登录的用户名和ID
                    currentUsername = username;
                    currentUserId = obj.get("user_id").getAsString(); // 假设响应中包含id字段
                    usernameField.clear();
                    passwordField.clear();
                    MainPanel.updateUserRegion();
                    //ChapterPanel.update();
                    cardLayout.show(cardPanel, "MAINPANEL");
                } else if ("invalid_credentials".equals(obj.get("code").getAsString())) {
                    showAlert("用户名或密码错误");
                } else {
                    showAlert("未知错误，请稍后再试");
                }
            } catch (Exception ex) {
                showAlert("网络异常，请检查连接");
                ex.printStackTrace();
            }
        });

        // 注册链接
        HBox registerBox = new HBox(5);
        registerBox.setAlignment(Pos.CENTER);

        Label registerLabel = new Label("还没有账号？");
        registerLabel.setFont(Font.font("KaiTi", 24));
        registerLabel.setTextFill(Color.rgb(0, 210, 211));

        Button registerButton = new Button("立即注册");
        registerButton.setFont(Font.font("KaiTi", FontWeight.BOLD, 24));
        registerButton.setTextFill(Color.rgb(0, 210, 211));
        registerButton.setStyle("-fx-background-color: transparent; -fx-underline: true;");
        registerButton.setOnAction(e -> cardLayout.show(cardPanel, "REGISTERPANEL"));

        registerBox.getChildren().addAll(registerLabel, registerButton);

        // 添加所有元素到登录面板
        VBox inputContainer = new VBox(20);
        inputContainer.setAlignment(Pos.CENTER);
        inputContainer.getChildren().addAll(usernameField, passwordField);

        loginBox.getChildren().addAll(loginTitle, inputContainer, loginButton, registerBox);
        return loginBox;
    }

    // 辅助方法：创建输入框
    private TextField createInputBox(String prompt) {
        TextField field = new TextField();
        field.setPromptText(prompt);
        field.setPrefSize(WIDTH/3, 75);
        field.setMaxWidth(WIDTH/3);
        field.setStyle(
                "-fx-background-color: rgba(99, 110, 114, 0.5); " +
                        "-fx-text-fill: white; " +
                        "-fx-prompt-text-fill: rgba(200, 200, 200, 0.7); " +
                        "-fx-border-radius: 5; " +
                        "-fx-background-radius: 5; " +
                        "-fx-padding: 0 10; " +
                        "-fx-font-size: 24px;"
        );
        return field;
    }

    // 辅助方法：创建密码框
    private PasswordField createPasswordBox(String prompt) {
        PasswordField field = new PasswordField();
        field.setPromptText(prompt);
        field.setPrefSize(WIDTH/3, 75);
        field.setMaxWidth(WIDTH/3);
        field.setStyle(
                "-fx-background-color: rgba(99, 110, 114, 0.5); " +
                        "-fx-text-fill: white; " +
                        "-fx-prompt-text-fill: rgba(200, 200, 200, 0.7); " +
                        "-fx-border-radius: 5; " +
                        "-fx-background-radius: 5; " +
                        "-fx-padding: 0 10; " +
                        "-fx-font-size: 24px;"
        );

        return field;
    }

    // 辅助方法：创建按钮
    private Button createButton(String text) {
        Button button = new Button(text);
//        button.setFont(javafx.scene.text.Font.font("KaiTi", javafx.scene.text.FontWeight.BOLD, 40));
//        button.setTextFill(javafx.scene.paint.Color.WHITE);
//        button.setPrefSize(WIDTH/3, 75);
//        button.setStyle("-fx-background-color: #6C5CE7; -fx-background-radius: 5;");

        // 添加悬停效果
        button.setOnMouseEntered(e -> {
            button.setStyle("-fx-background-color: #8C7DF7; -fx-background-radius: 5;");
            button.setEffect(new javafx.scene.effect.DropShadow(10, javafx.scene.paint.Color.rgb(108, 92, 231, 0.5)));
        });

        button.setOnMouseExited(e -> {
            button.setStyle("-fx-background-color: #6C5CE7; -fx-background-radius: 5;");
            button.setEffect(null);
        });
        button.setFont(javafx.scene.text.Font.font("KaiTi", javafx.scene.text.FontWeight.BOLD, 40));
        button.setTextFill(javafx.scene.paint.Color.WHITE);
        button.setPrefSize(WIDTH/3, 75);
        button.setStyle("-fx-background-color: #6C5CE7; -fx-background-radius: 5;");


        return button;
    }

    private void showAlert(String message) {
        javafx.scene.control.Alert alert = new javafx.scene.control.Alert(javafx.scene.control.Alert.AlertType.INFORMATION);
        alert.setTitle("提示");
        alert.setHeaderText(null);
        alert.setContentText(message);

        // 设置对话框样式
        alert.getDialogPane().setStyle("-fx-background-color: #2D3436; -fx-text-fill: white;");
        alert.getDialogPane().lookupButton(javafx.scene.control.ButtonType.OK).setStyle("-fx-background-color: #6C5CE7; -fx-text-fill: white;");

        // 设置对话框字体
        javafx.scene.control.DialogPane dialogPane = alert.getDialogPane();
        for (javafx.scene.Node node : dialogPane.getChildren()) {
            if (node instanceof javafx.scene.control.Label) {
                ((javafx.scene.control.Label) node).setFont(javafx.scene.text.Font.font("KaiTi", 24));
                ((javafx.scene.control.Label) node).setTextFill(javafx.scene.paint.Color.WHITE);
            }
        }

        alert.showAndWait();
    }


    // 登录验证方法（示例）
    private boolean validateLogin(String username, String password) {
        // 实际项目中应连接数据库验证
        return !username.isEmpty() && !password.isEmpty();
    }

    @Override
    public void showPanel() {
        cardLayout.show(cardPanel, "LOGINPANEL");
    }

    @Override
    public void cleanup() {

    }
}